package demo06238;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SafeTicketSystem {
        private int ticketCount;
        private final Lock lock = new ReentrantLock();

        public SafeTicketSystem(int ticketCount) {
            this.ticketCount = ticketCount;
        }


        public synchronized void sellTicketSyncMethod() {
            if (ticketCount > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ticketCount--;
                System.out.println(Thread.currentThread().getName() + "售出1张票(同步方法)，剩余：" + ticketCount);
            } else {
                System.out.println(Thread.currentThread().getName() + "票已售罄");
            }
        }

        public void sellTicketSyncBlock() {
            synchronized(this) {
                if (ticketCount > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticketCount--;
                    System.out.println(Thread.currentThread().getName() + "售出1张票(同步块)，剩余：" + ticketCount);
                } else {
                    System.out.println(Thread.currentThread().getName() + "票已售罄");
                }
            }
        }

        public void sellTicketWithLock() {
            lock.lock();
            try {
                if (ticketCount > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ticketCount--;
                    System.out.println(Thread.currentThread().getName() + "售出1张票(Lock)，剩余：" + ticketCount);
                } else {
                    System.out.println(Thread.currentThread().getName() + "票已售罄");
                }
            } finally {
                lock.unlock();
            }
        }

        public int getTicketCount() {
            return ticketCount;
        }
    }


